package cn.shop.gameapi.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @author : 李一涵
 * @date : Created in 2022-1-11 14:03
 * @description :
 */

@Component
public class IdUtil {

    private static final Logger LOG = LoggerFactory.getLogger(IdUtil.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long getId(long uid) {
        LocalDate now = LocalDate.now();
        LocalTime time = LocalTime.now();
        String head = now.format(DateTimeFormatter.ofPattern("yyMMdd"));
        String hour = time.format(DateTimeFormatter.ofPattern("HH"));

        long index = ObjectUtil.defaultIfNull(stringRedisTemplate.opsForValue().increment(head + hour + uid), 0L);
        if (index == 0) {
            LOG.warn("生成id错误 {} {} {}", now, time, uid);
        }
        stringRedisTemplate.expire(head + hour + uid, 1, TimeUnit.HOURS);
        String mid = StrUtil.fillBefore(String.valueOf(uid), '0', 4);
        String end = StrUtil.fillBefore(String.valueOf(index), '0', 5);
        return Long.parseLong(head + mid + hour + end);
    }
}
